import { HttpException, Injectable } from '@nestjs/common';
import { CreateArticleDto } from './dto/create-article.dto';
import { PrismaService } from 'src/prisma/prisma.service';
import { resultUtil } from 'src/utils/result';
import * as dayjs from 'dayjs';

@Injectable()
export class ArticleService {
  constructor(private readonly prismaService: PrismaService) {}
  /**
   * 创建文章
   */
  async createArticle(createArticelDto: CreateArticleDto, authorId: number, role: string) {
    try {
      await this.prismaService.article.create({
        data : {
          ...createArticelDto,
          authorId: +authorId,
          authorRole: role ?? ''
        },
      });
      return resultUtil('', '000000');
    } catch {
      new HttpException('新增失败', 400);
    }
  }

  /**
   * 文章查询
   */
  async queryArticel(queryInfo, authorId: number, role: string) {
    const { title, content, currentPage, pageSize, publish } = queryInfo;
    const skip = (currentPage - 1) * pageSize;

    const where :any = {};
    if (title) {
      where.title = { contains: title };
    }
    if (content) {
      where.content = { contains: content };
    }
    // 如果不是超级管理员的角色就只能看自己的文章
    if (role !='admin') {
      where.authorId = authorId
    }
    if (+publish) {
      where.publish = true
    }
    const [records, total] = await Promise.all([
      this.prismaService.article.findMany({
        where,
        skip,
        take: pageSize,
        orderBy: {
          id: 'desc',
        },
        select: {
          id: true,
          content: true,
          img: true,
          title: true,
          authorId: true,
          createdAt: true,
          author: true,
          type: true,
          tag: true,
          publish: true,
          abstract: true
        },
      }),
      this.prismaService.article.count({ where }),
    ]);
    return resultUtil('', '000000', {
      records: records?.map((item: any) => {
        let result = {
          ...item,
          createdAt: dayjs(item.createdAt).format('YYYY-MM-DD HH:mm:ss'),
          username: item.author.username,
          // disabled: item.authorId != authorId
        }
        delete result.author
        return result
      }),
      total: total,
    });
  }

  /**
   * 删除文章
   */
  async delete(id: number) {
    await this.prismaService.article.delete({
      where: { id: +id },
    });
    return resultUtil('', '000000');
  }

  /**
   * 批量删除
  */
  async batchDelete(ids: any) {
    await this.prismaService.article.deleteMany({
      where: {
        id: {
          in: [...ids]
        }
      }
    })
    return resultUtil('', '000000');
  }

  /**
   * 更新文章
   */
  async update(upadteInfo) {
    delete(upadteInfo.username)
    await this.prismaService.article.update({
      where: { id: +upadteInfo.id },
      data: {
        ...upadteInfo,
        id: +upadteInfo.id,
      },
    });
    return resultUtil('', '000000');
  }

  /**
   * 发布文章
  */
 async publish(info) {
  await this.prismaService.article.update({
    where: { id: +info.id },
    data: {
      publish: info.publish
    },
  });
  return resultUtil('', '000000');
 }

  /**
   * 根据文章id查询文章详情
   */
  async queryDetails(id) {
    const res = await this.prismaService.article.findUnique({
      where: { id },
      select: {
        id: true,
        content: true,
        img: true,
        title: true,
        authorId: true,
        createdAt: true,
        author: true,
        type: true,
        tag: true,
        publish: true,
        abstract: true
      }
    });
    const result = {
      username: res?.author.username,
      ...res,
    }
    delete(result.author)
    return resultUtil('', '000000', result);
  }

  /**
   * 对文章进行归档（按照年份月份归档）
  */
  async findAllGroupedByYearMonth() {
    // 查询所有文章
    const result = await this.prismaService.article.findMany();
    // 按照年月份来归档
    const groupedPosts = {};
    result.forEach(item => {
      const createdAt = item.createdAt;
      const yearMonth = `${createdAt.getFullYear()}-${(createdAt.getMonth() + 1).toString().padStart(2, '0')}`;
      if (!groupedPosts[yearMonth]) {
        groupedPosts[yearMonth] = [];
      }
      groupedPosts[yearMonth].push(item);
    });
    return resultUtil('', '000000', groupedPosts)
  }
}
